define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    var modals = require("./template/modal.html");
    var postage = require("./template/postage.html");
    var givepacket = require("./template/givepacket.html");
    var packet = require("./template/packet.html");
    var coupon = require("./template/coupon.html");
    var activity_selectid=null;
    template.helper('activity_selected', function(id, selectid) {
        var flag=""
        $.each(selectid,function(){
            for (var key in this) {
                if (key) {
                    if (key == id) {
                        flag="checked='checked'";
                    }
                }
            }
        });
        return flag;
    });
    exports.init = function(el, button) {
        $("#ajaxModalLink").remove();
        var $modal = $('<div class="modal fade" id="ajaxModalLink"><div class="modal-body "></div></div>');
        $(document).append($modal);
        $modal.modal();
        var path = button.data("path"),
            types = button.data("type"),
            title = button.data("title") || "选择活动",
            search = button.data("search") || false,
            update = button.data("update"),
            subtitle=button.data("subtitle") || "",
            tempid=button.data("tempid"),
            targets=button.data("target"),
            name = "" || "活动";
        switch (types) {
            case "coupon":
                name = "活动";
                break;
            case "packet":
                name = "活动";
                break;
            case "postage":
                name = "活动";
                break;
            case "givepacket":
                name = "活动";
                break;
        }
        var data = {
            "path": path,
            "types": types,
            "name": name,
            "search":search,
            "title": title+subtitle
        }
        $modal.append2(template.compile(modals)(data), function() {
            var $fn = $("#js_allActivity", $modal),$form=$(".search-form",$modal);
            var data = $form.serialize();
            init(path, data, $fn, types,selectid(button));
        });

        function init(path, datas, target, types,selectid) {
            method.post(path, function(data) {
                if (config.issucceed(data)) {
                    data.types = types;
                    data.selectid=selectid;
                    activity_selectid=selectid;
                    data.data.pagelist = pageDate(data.data);
                    switch (types) {
                        case "postage":
                            target.html(template.compile(postage)(data));
                            break;
                        case "packet":
                            target.html(template.compile(packet)(data));
                            break;
                        case "givepacket":
                            target.html(template.compile(givepacket)(data));
                            break;
                        case "coupon":
                            target.html(template.compile(coupon)(data));
                            break;
                    }
                    allcheck();
                } else {
                    config.msg.error(data.message);
                }
            }, config.lang.exception, false, datas);
        }

        function pageDate(data) {
            var pagelist = [],
                total = data.totalPage,
                current = data.currentPage;
            if (total > 0) {
                if (total - current >= 2) {
                    var start = 1,
                        end = 5;
                    start = (current - 2) > 0 ? (current - 2) : 1;
                    end = start + 4;
                    for (var i = start; i <= end; i++) {
                        if (i > 0 && i <= total) {
                            pagelist.push(i);
                        }
                    }
                } else {
                    var start = 1,
                        end = 5;
                    end = (current + 2) <= total ? (current + 2) : total;
                    start = end - 4;
                    for (var i = start; i <= end; i++) {
                        if (i > 0 && i <= total) {
                            pagelist.push(i);
                        }
                    }
                }
            }
            return pagelist;
        }
        function selectid(button){
            var $target=$(button.data("target"),el),arr=[];
            $target.find("li.dd-item").each(function(){
                var $this=$(this),$input=$("input[type='hidden']",$this),val=$input.val(),name=$input.data("names");
                arr.push(getjson(val,name));
            });
            return arr
        }
        function getjson(key,value){
            var b = eval("(" + "{\"" + key + "\": \"" + value + "\"}" + ")");
            return b;
        }
        
        $modal.on("click", ".js_allactivity_select", function() {
            var $this = $(this),result=[],d={};
            $.each(activity_selectid,function(){
                for (var key in this) {
                    if(key){
                        result.push({
                            id: key,
                            name: this[key]
                        });
                    }
                }
            });
            d.result=result;
            $(targets,el).html(template(tempid,d));
            var done = function() {
                $(".js_item_list").nestable({
                    maxDepth: 1
                });
                $('.dd-handle a', el).on('mousedown', function(e) {
                    e.stopPropagation();
                });
            }
            require.async("nestable", done);
            button.find("span").html(update);
            $modal.modal("hide");
        });
        $modal.on("click", "table td input", function() {
            setDate(this);
        });
        function setDate(obj){
            var $this=$(obj),flag=$this.prop("checked"),val=$this.val(),name=$this.data("names"),
            $table=$this.closest("table");
            if(flag){
                if($this.attr("type")=="radio"){
                    activity_selectid=[getjson(val,name)];
                }else{
                    activity_selectid.push(getjson(val,name));
                }
                allcheck();
            }else{
                $table.find("th input").prop("checked",false);
                $.each(activity_selectid,function(i){
                    for (var key in this) {
                        if (key) {
                            if(key==val){
                                activity_selectid.splice(i,1);
                            }
                        }
                    }
                });
            }
        }
        function unique(arr) {
            var result = [],
                hash = {};
            for (var i = 0,len=arr.length;i<len;i++) {
                for (var key in arr[i]) {
                    if(key){
                        if (!hash[key]) {
                            result.push(arr[i]);
                            hash[key] = true;
                        }
                    }
                }
            }
            return result;
        }
        function allcheck(){
            var $table=$("#js_allActivity table"),$inputs=$("input",$table),
            len=$inputs.length,clen=0;
            $inputs.each(function(){
                if($(this).prop("checked")){
                    clen++;
                }
            });
            if(clen==len-1){
                $("th input",$table).prop("checked",true);
            }
        }
        $modal.on("click", "table th input", function() {
            var $this=$(this),flag=$this.prop("checked"),$table=$this.closest('table'),
            $inputs=$table.find("td input");
            if(flag){
                $inputs.prop("checked",true);
            }else{
                $inputs.prop("checked",false);
            }
            $inputs.each(function(){
                setDate(this);
            });
            activity_selectid=unique(activity_selectid);
        });
        $modal.on("click", "footer[data-type='ajaxPage'] a", function() {
            var $this = $(this),
                $li = $this.closest('li'),
                flag = $li.hasClass('disabled'),
                active = $li.hasClass('active'),
                $tab = $this.closest("div.modal-body"),
                $form = $tab.find("form"),
                type = $form.data("type"),
                path = $form.data("path"),
                $page = $(".js_alllink_page", $form),
                $js_allActivity = $tab.find("#js_allActivity"),
                pagenum = $this.data("pageNum");
            path += "&submittype=page";
            if (!flag && !active) {
                $page.val(pagenum);
                $modal.find("footer[data-type='ajaxPage'] li.active").removeClass("active");
                $li.addClass('active');
                var data = $form.serialize();
                if ($js_allActivity.length > 0) {
                    init(path, data, $js_allActivity, types,selectid(button));
                }
            }
        });
        $modal.on("click", "button[data-type='ajaxSearch']", function() {
            var $this = $(this),
                $tab = $this.closest("div.modal-body"),
                $form = $this.closest('form'),
                path = $form.data("path"),
                $page = $(".js_alllink_page", $form),
                $js_allActivity = $tab.find("#js_allActivity");
            $page.val(1);
            var data = $form.serialize();
            path += "&submittype=search";
            if ($js_allActivity.length > 0) {
                init(path, data, $js_allActivity,types,selectid(button));
            }
        });
    }
});